#!/usr/bin/python
# -*- coding:utf-8 -*-
import ConfigParser
from ext import logging

import MySQLdb


class HtmlOuter(object):
    def __init__(self):
        cf = ConfigParser.ConfigParser()
        cf.read('config.ini')
        host = cf.get('db', 'host')
        user = cf.get('db', 'user')
        pwd = cf.get('db', 'passwd')
        db = cf.get('db', 'db')
        self.conn = MySQLdb.connect(host=host, user=user, passwd=pwd, db=db, charset="utf8")
        self.cursor = self.conn.cursor()

    def write(self, data):
        if data.get('type') == 1:
            district_list = data.get('district_list')
            self.__write_data_list(district_list.get('table_name'), district_list.get('data_list'))
            street_list = data.get('street_list')
            self.__write_data_list(street_list.get('table_name'), street_list.get('data_list'))
        elif data.get('type') == 2:
            co_list = data.get('co_list')
            self.__write_data_list(co_list.get('table_name'), co_list.get('data_list'))
        elif data.get('type') == 3:
            try:
                data_column = data.get('data').get('column')
                self.__update(data.get('data').get('table_name'), data_column)
            except Exception, e:
                logging.error(e.message)

    def __write_data_list(self, table_name, data_list):
        try:
            for data in data_list:
                self.__write(table_name, data)
        except Exception, e:
            logging.error(e.message)

    def __write(self, table_name, data):
        sql = 'insert into %s(' % table_name
        names = data.keys()
        for name in names:
            sql += name + ','
        sql = sql[:-1] + ') values('
        for name in names:
            sql += '"%s",' % data[name].replace('\n', ' ')
        sql = sql[:-1] + ')'
        logging.info(sql)
        self.cursor.execute(sql)
        self.conn.commit()

    def __update(self, table_name, data):
        sql = 'UPDATE %s SET' % table_name
        names = data.keys()
        for name in names:
            sql += ' %s="%s",' % (name, data.get(name))
        sql = sql[:-1]
        sql += ' where id="%s"' % data.get('id')
        logging.info(sql)
        self.cursor.execute(sql)
        self.conn.commit()
